import { defineStore } from "pinia";
import { store } from "/@/store";
// import { getBtnAuthByRouteName } from "/@/api/mock";
import router, {
  constantRoutesArr,
  ascending,
  filterTree
} from "/@/router/index";
import { postResourceAuth } from "/@/api/resource";
import { storageLocal } from "/@/utils/storage";
import { cloneDeep } from "lodash-es";

import axios from "axios";
import { setAccToken } from "/@/utils/ecm";
import { identifyHowxm } from "howxm-js";

export const usePermissionStore = defineStore({
  id: "pure-permission",
  state: () => ({
    constantRoutes: constantRoutesArr, //静态路由
    wholeRoutes: [],
    buttonAuth: [],
    userName: "",
    userId: "",
    menusTree: []
  }),
  actions: {
    asyncActionRoutes(routes) {
      if (this.wholeRoutes.length > 0) return;
      this.wholeRoutes = filterTree(
        ascending(constantRoutesArr.concat(routes))
      );
      // this.wholeRoutes = ascending(this.constantRoutes.concat(routes)).filter(
      //   v => {
      //     if (v.children) {
      //       v.children = v.children.filter(c => c.meta?.showLink);
      //     }
      //     return v.meta?.showLink;
      //   }
      // );
      // const newArr = this.wholeRoutes.map(item => {
      //   if (item.children.length === 1) {
      //     // item = item.children[0];
      //     item.path = item.children[0].path;
      //     item.children = [];
      //   }
      //   return item;
      // });
      // this.wholeRoutes = newArr;

      this.menusTree = cloneDeep(this.wholeRoutes);
      // console.log(this.wholeRoutes, "this.wholeRoutes");

      // 原来是重route.meta中获取权限
      // const getButtonAuth = (arrRoutes: Array<string>) => {
      //   if (!arrRoutes || !arrRoutes.length) return;
      //   arrRoutes.forEach((v: any) => {
      //     if (v.meta && v.meta.authority) {
      //       this.buttonAuth.push(...v.meta.authority);
      //     }
      //     if (v.children) {
      //       getButtonAuth(v.children);
      //     }
      //   });
      // };
      //
      // getButtonAuth(this.wholeRoutes);
    },

    // setUserName(payload) {
    //   this.userName = payload;
    // },
    async changeSetting(routes) {
      await this.resetSetting();
      await this.asyncActionRoutes(routes);
    },

    // 重置路由及权限
    async resetSetting() {
      this.wholeRoutes = [];
      this.buttonAuth = [];
    },

    // ldap 登录处理
    async ldapLogin(code, state) {
      let authorization = "";
      if (storageLocal.getItem("rdms-info")) {
        authorization = storageLocal.getItem("rdms-info")?.accessToken;
      }
      const baseUrl = import.meta.env.VITE_BASE_URL;

      const sourceUrl = `${baseUrl}/rdms-admin/sysResource/resourceAuth`;
      const headerConfig = {
        code: code,
        state: state
      };
      if (authorization) {
        //@ts-ignore
        headerConfig.Authorization = authorization;
      }
      try {
        const res = await axios.post(
          sourceUrl,
          { groupUrl: "/project/kanban" },
          {
            headers: headerConfig
          }
        );

        console.log(res.headers, "response");

        if (res.headers.name) {
          const info = {
            username: decodeURI(res.headers?.username),
            name: decodeURI(res.headers?.name),
            userId: res.headers?.userid,
            accessToken: res.headers?.token
          };
          this.userName = decodeURI(res.headers?.name);
          this.userId = decodeURI(res.headers?.userid);
          storageLocal.setItem("rdms-info", info);
          setAccToken();
          // 浩客identify 用户身份信息传递
          identifyHowxm({
            uid: info.username, // 用户唯一ID, 默认字段, 必填，string 类型
            name: info.name // 名称，默认字段，非必填，string 类型
          });
        }

        console.log(storageLocal.getItem("rdms-info"), "info");

        if (res.data?.code === 200 && res.data.data != null) {
          this.buttonAuth =
            res.data.data.length &&
            res.data.data.map(item => {
              return item.resourceKey;
            });
        } else {
          this.buttonAuth.length = 0;
        }
        return true;
      } catch (error) {
        console.error(error.response);
        const code = error?.response?.status;
        if ([401, 403].includes(code)) {
          storageLocal.removeItem("rdms-info");

          // router.replace({
          //   path: "/login"
          // query: { redirect: location.href }
          // });
          // }
          await this.ldapLogin(headerConfig.code, headerConfig.state);
        }
        return false;
      }
    },

    async getBtnAuth(path: string, query?: any) {
      // 现在是直接根据下一次要进入页面的name去后台查询权限
      if (path === "/project/kanban" && query.code) {
        await this.ldapLogin(query.code, query.state);
        return true;
      } else {
        try {
          const res = await postResourceAuth({ groupUrl: path });
          if (res.code === 200 && res.data != null) {
            this.buttonAuth =
              res.data.length &&
              res.data.map(item => {
                return item.resourceKey;
              });
          } else {
            this.buttonAuth.length = 0;
          }
          return true;
        } catch (error) {
          console.error(error);
          const code = error?.response?.status;
          if ([401, 403].includes(code)) {
            storageLocal.removeItem("rdms-info");

            router.replace({
              path: "/login"
              // query: { redirect: location.href }
            });
            // }
          }
          return Promise.reject(error);
          // return false;
        }
      }
    }
  }
});

export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
